import React from 'react'

interface UserContext {
    username:string,
    setUsername:(value:string) => void
}
// 定义上下文里的数据
const MyContext = React.createContext<UserContext>({
    username:'',
    setUsername:(value) => {}
})
export const MyContextProvider = (props:any) => {
    const [username,setUsername] = React.useState("json doe")
    return (
        // Provider 组件能力
        // <Provider store={store}/>
     <MyContext.Provider value={{username,setUsername}}>
        {props.children}
     </MyContext.Provider>   
    )
}
const MyEditComponent = () => {
    const {username,setUsername} = React.useContext(MyContext);
    const [newUsername,setNewUsername] = React.useState("");
    const handleChange = (e) => {
        setNewUsername(e.target.value)
    }
    return (
        <div>
            <input placeholder={username} onChange={handleChange} 
            />
            <button onClick={() => setUsername(newUsername)}>save</button>
        </div>
    )
}
export const NewDemo = () => {
    const myContext = React.useContext(MyContext);
  return (
    <div>
        <p>{myContext.username}</p>
        <MyEditComponent/>
    </div>
  )
}

